package com.xc.erp.modules.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xc.erp.common.annotation.Log;
import com.xc.erp.common.utils.SecurityUtils;
import com.xc.erp.modules.erp.domain.dto.LoginUser;
import com.xc.erp.modules.erp.domain.pojo.JshUser;
import com.xc.erp.modules.erp.mapper.JshUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 登录业务
 *
 * @author wjw 2022/10/27
 * @DateTime: 2022/10/27 17:06
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private JshUserMapper jshUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<JshUser> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name",username);
        JshUser user = jshUserMapper.selectOne(wrapper);
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 查询权限信息
        List<String> perms = null;
        if(SecurityUtils.isAdmin(user.getId())){
            perms = jshUserMapper.selectPermsAll();
        }else{
            perms = jshUserMapper.selectPermsByUserId(user.getId());
        }

        LoginUser loginUser = new LoginUser(user,perms);
        return loginUser;
    }
}
